package com.bayair.doctor.base.component;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import com.bayair.doctor.App;
import com.bayair.doctor.R;
import com.bayair.doctor.biz.helper.SpSetting;
import com.bayair.doctor.biz.helper.StatusManager;
import com.bayair.doctor.biz.helper.net_change.NetworkCallbackUtil;
import com.bayair.doctor.ui.inquiry_record.SessionDataKit;
import com.bayair.doctor.ui.login.LoginActivity;
import com.bayair.doctor.utils.log.KLog;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.tencent.imsdk.TIMConversation;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IMEventListener;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.Toolbar;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

public abstract class BaseActivity extends CommonActivity implements OnTitleBarListener, NetworkCallbackUtil.ConnectivityChangeCallback {

    /**
     * 标题栏对象
     */
    private TitleBar mTitleBar;
    /**
     * 状态栏沉浸
     */
    private ImmersionBar mImmersionBar;

    protected View statusBarView;
    protected Toolbar toolbar;

    // 监听做成静态可以让每个子类重写时都注册相同的一份。
    private static IMEventListener mIMEventListener = new IMEventListener() {
        @Override
        public void onForceOffline() {
            //IM账号被顶下
            ToastUtil.toastLongMessage("您的帐号已在其它终端登录");
            //测试时关闭
            logout(App.getContext());
        }

        @Override
        public void onRefreshConversation(List<TIMConversation> conversations) {
            //会话刷新
            SessionDataKit.instance().onRefreshConversation(conversations);
        }
    };
    //登录状态的Activity都要设置成true(默认未true),来完成被踢下线等监听处理。
    //login和splash 等登录应该设置为false
    protected boolean isNeedAddIMEventListener() {
        return true;
    }

    public static void logout(Context context) {
        SpSetting.setLogin(false);//被顶下，重置标志login标志位

        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置IM状态监听
        if (isNeedAddIMEventListener()) TUIKit.addIMEventListener(mIMEventListener);

        //网络状态监听
        NetworkCallbackUtil.addNetworkCallback(this.getClass().getName(), this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkCallbackUtil.removeNetworkCallback(this.getClass().getName());
    }

    @Override
    protected void initTitleBar() {
        //初始化标题栏，并设置监听
        if (getTitleId() > 0) {
            // 勤快模式
            View view = findViewById(getTitleId());
            if (view instanceof TitleBar) {
                mTitleBar = (TitleBar) view;
            }
        } else if (getTitleId() == 0) {
            // 懒人模式
            mTitleBar = findTitleBar(getContentView());
        }
        if (mTitleBar != null) {
            mTitleBar.setOnTitleBarListener(this);
        }

        //设置沉侵式标题
        initImmersion();
    }

    /**
     * 获取标题栏 id
     */
    protected int getTitleId() {
        return 0;
    }


    /**
     * 递归获取 ViewGroup 中的 TitleBar 对象
     */
    static TitleBar findTitleBar(ViewGroup group) {
        for (int i = 0; i < group.getChildCount(); i++) {
            View view = group.getChildAt(i);
            if ((view instanceof TitleBar)) {
                return (TitleBar) view;
            } else if (view instanceof ViewGroup) {
                TitleBar titleBar = findTitleBar((ViewGroup) view);
                if (titleBar != null) {
                    return titleBar;
                }
            }
        }
        return null;
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersion() {
        // 初始化沉浸式状态栏
        if (immersionBarEnabled()) {
            statusBarConfig().init();
            //适配渐变色状态栏、侧滑返回
            //statusBarView、toolbar解决布局顶部和状态栏重叠，xml中设置之后不会重叠
            statusBarView = findViewById(R.id.status_bar_view);
            toolbar = findViewById(R.id.toolbar);
            if (statusBarView != null) {
                ImmersionBar.setStatusBarView(this, statusBarView);
            } else if (toolbar != null) {
                ImmersionBar.setTitleBar(this, toolbar);
            } else if (getTitleId() > 0) {
                ImmersionBar.setTitleBar(this, findViewById(getTitleId()));
            } else if (mTitleBar != null) {
                ImmersionBar.setTitleBar(this, mTitleBar);
            }
        }
    }

    /**
     * 是否使用沉浸式状态栏
     */
    public boolean immersionBarEnabled() {
        return true;
    }

    /**
     * 获取状态栏字体颜色
     */
    public boolean statusBarDarkFont() {
        // 返回真表示黑色字体 (false/白色)
        return true;
    }

    /**
     * 初始化沉浸式状态栏
     */
    protected ImmersionBar statusBarConfig() {
        // 在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this)
                .keyboardEnable(false)
                // 默认状态栏字体颜色为黑色
                .statusBarDarkFont(statusBarDarkFont())
                .statusBarColor(R.color.transparent);
        return mImmersionBar;
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(@StringRes int id) {
        setTitle(getString(id));
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (mTitleBar != null) {
            mTitleBar.setTitle(title);
        }
    }

    /**
     * 设置标题栏的左标题
     */
    public void setLeftTitle(int id) {
        if (mTitleBar != null) {
            mTitleBar.setLeftTitle(id);
        }
    }

    public void setLeftTitle(CharSequence text) {
        if (mTitleBar != null) {
            mTitleBar.setLeftTitle(text);
        }
    }

    public CharSequence getLeftTitle() {
        if (mTitleBar != null) {
            return mTitleBar.getLeftTitle();
        }
        return "";
    }

    /**
     * 设置标题栏的右标题
     */
    public void setRightTitle(int id) {
        if (mTitleBar != null) {
            mTitleBar.setRightTitle(id);
        }
    }

    public void setRightTitle(CharSequence text) {
        if (mTitleBar != null) {
            mTitleBar.setRightTitle(text);
        }
    }

    public CharSequence getRightTitle() {
        if (mTitleBar != null) {
            return mTitleBar.getRightTitle();
        }
        return "";
    }

    /**
     * 设置标题栏的左图标
     */
    public void setLeftIcon(int id) {
        if (mTitleBar != null) {
            mTitleBar.setLeftIcon(id);
        }
    }

    public void setLeftIcon(Drawable drawable) {
        if (mTitleBar != null) {
            mTitleBar.setLeftIcon(drawable);
        }
    }

    @Nullable
    public Drawable getLeftIcon() {
        if (mTitleBar != null) {
            return mTitleBar.getLeftIcon();
        }
        return null;
    }

    /**
     * 设置标题栏的右图标
     */
    public void setRightIcon(int id) {
        if (mTitleBar != null) {
            mTitleBar.setRightIcon(id);
        }
    }

    public void setRightIcon(Drawable drawable) {
        if (mTitleBar != null) {
            mTitleBar.setRightIcon(drawable);
        }
    }

    @Nullable
    public Drawable getRightIcon() {
        if (mTitleBar != null) {
            return mTitleBar.getRightIcon();
        }
        return null;
    }

    @Nullable
    public TitleBar getTitleBar() {
        return mTitleBar;
    }

    /**
     * {@link OnTitleBarListener}
     */

    /**
     * TitleBar 左边的View被点击了
     */
    @Override
    public void onLeftClick(View v) {
        onBackPressed();
    }

    /**
     * TitleBar 中间的View被点击了
     */
    @Override
    public void onTitleClick(View v) {
    }

    /**
     * TitleBar 右边的View被点击了
     */
    @Override
    public void onRightClick(View v) {
    }

    //---------------通用配置----------------------------------------------

    public void startActivityWithAnim(Class<? extends Activity> cls) {
        super.startActivity(cls);
        showTransferAnimation = true;
    }

    public void startActivityForResultWithAnim(Class<? extends Activity> cls, ActivityCallback callback) {
        super.startActivityForResult(new Intent(this, cls), null, callback);
        showTransferAnimation = true;
    }

    public void finishWithAnim() {
        super.finish();
        showTransferAnimation = true;
    }

    private boolean showTransferAnimation;

    //*** startActivity--> 最后都会走如下方法
    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        if (showTransferAnimation) {
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            showTransferAnimation = false;
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (showTransferAnimation) {
            overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            showTransferAnimation = false;
        }
    }

    /**
     * 显示吐司
     */
    public void toast(CharSequence text) {
        ToastUtils.showShort(text);
    }

    /**
     * 显示吐司
     */
    public void toastLong(CharSequence text) {
        ToastUtils.showLong(text);
    }

    /**
     * 打印日志
     */
    public void log(Object object) {
        KLog.i(getClass().getSimpleName(), object != null ? object.toString() : "null");
    }

    public void loge(Object object) {
        KLog.e(getClass().getSimpleName(), object != null ? object.toString() : "null");
    }


    @Override
    protected void onStop() {
        super.onStop();
        mStatusManager.showComplete();
    }

    private final StatusManager mStatusManager = new StatusManager();

    /**
     * 显示加载中
     */
    public void showLoading() {
        mStatusManager.showLoading(this);
    }

    public void showLoading(@StringRes int id) {
        mStatusManager.showLoading(this, getString(id));
    }

    public void showLoading(CharSequence text) {
        mStatusManager.showLoading(this, text);
    }

    /**
     * 显示加载完成
     */
    public void showComplete() {
        mStatusManager.showComplete();
    }

    /**
     * 显示空提示
     */
    public void showEmpty() {
        mStatusManager.showEmpty(getContentView());
    }

    /**
     * 显示错误提示
     */
    public void showError() {
        mStatusManager.showError(getContentView());
    }

    /**
     * 显示自定义提示
     */
    public void showLayout(@DrawableRes int drawableId, @StringRes int stringId) {
        mStatusManager.showLayout(getContentView(), drawableId, stringId);
    }

    public void showLayout(Drawable drawable, CharSequence hint) {
        mStatusManager.showLayout(getContentView(), drawable, hint);
    }


    @Override
    public void onAvailable(Network network, NetworkInfo networkInfo) {
        KLog.i("网络可用....");
    }

    @Override
    public void onLost(Network network, NetworkInfo networkInfo) {
        KLog.i("网络丢失....");
    }
}
